﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.IO;
using nwrole.lib;

namespace nwrole.service
{
    partial class PluginService : ServiceBase
    {
        private Guid Id;
        private int Port;
        private ServiceManager manager;
        private Uri baseAddress;
        private ServiceHost serviceHost;

        public PluginService(Guid id, int port)
        {
            Id = id;
            Port = port;
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            EventLogger.LogInformation("PluginService.OnStart", String.Format("Starting Plugin service '{0}' ({1}).", Id, Port));
            try
            {
                if (serviceHost != null)
                    serviceHost.Close();
                if (manager != null)
                    manager.OnStop();

                manager = new ServiceManager(Id);
                baseAddress = new Uri("net.tcp://localhost:" + Port.ToString());
                serviceHost = new ServiceHost(manager, baseAddress);
                NetTcpBinding binding = new NetTcpBinding();
                binding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
                binding.MaxReceivedMessageSize = 2147483647;
                serviceHost.AddServiceEndpoint(typeof(IServiceManager), binding, Id.ToString("N"));
                serviceHost.Open();

                manager.OnStart();
            }
            catch (Exception exception)
            {
                EventLogger.LogException("PluginService.OnStart", exception);
            }
            EventLogger.LogInformation("PluginService.OnStart", String.Format("Started Plugin service '{0}' ({1}).", Id, Port));
        }

        protected override void OnStop()
        {
            EventLogger.LogInformation("PluginService.OnStop", String.Format("Stopping Plugin service '{0}' ({1}).", Id, Port));
            if (serviceHost != null)
            {
                try
                {
                    manager.OnStop();
                    serviceHost.Close();
                    manager = null;
                    serviceHost = null;
                }
                catch (Exception exception)
                {
                    EventLogger.LogException("PluginService.OnStop", exception);
                }
                EventLogger.LogInformation("PluginService.OnStop", String.Format("Stopped Plugin service '{0}' ({1}).", Id, Port));
            }
        }
    }
}
